<?php
class Shop extends Model
{
    public static function addOrder($user, $address, $phone)
    {
        $db = new Database();
        $newId = self::genNewOrderId();

        $db->run('INSERT INTO dondathang(ddh_id, u_id, ddh_ngaydh, ddh_diachigh, ddh_sodtnh, ddh_trangthaigh, ddh_trangthaixn) ' .
            'VALUES(:ddh_id, :uid, NOW(), :add, :phone, 0, 0)', array(
            'ddh_id' => $newId,
            'uid' => $user,
            'add' => $address,
            'phone' => $phone
        ));
        return $newId;
    }

    private static function genNewOrderId()
    {
        $db = new Database();
        $time = date('my');
        $max = $db->executeScalar('SELECT MAX(ddh_id) FROM dondathang WHERE ddh_id LIKE :id',
            array('id' => $time . '___'));
        $max || $max = 1;
        return $time . str_pad(substr($max, 4) + 1, 3, "0", STR_PAD_LEFT);
    }

    public static function addOrderDetail($orderId, $items)
    {
        $db = new Database();
        foreach ($items as $item) {
            $db->run('INSERT INTO chitietddh (dt_id, ddh_id, ctddh_soluongdh, ctddh_dongiadh) ' .
                'VALUES (:item_id, :order_id, :quantity, :price)', array(
                'item_id' => $item['id'],
                'order_id' => $orderId,
                'quantity' => $item['quantity'],
                'price' => $item['_price']
            ));
        }
    }
}